import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_elm/network/user_api.dart';

import '../components/confirmDialog.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key, required this.title});
  final String title;

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  GlobalKey _formKey =GlobalKey<FormState>();
  UserApi userApi = UserApi();
  // 单选框这里的默认值，不能放在build里面定义。否则每次重新构建之后虽然sex值更改，
  // 但是在build中，又重新设置为默认值。所以就会显示没有更改。
  int sex = 1;
  TextEditingController _phoneController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  TextEditingController _pwdConfirmController = TextEditingController();
  TextEditingController _unameController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueAccent.shade400,
        title: Text("${widget.title}",style: TextStyle(color: Colors.white),),
        centerTitle: true,
        // 取消左上角返回箭头
        automaticallyImplyLeading: false,
      ),

      body: Container(
        margin: EdgeInsets.all(15.0),
        child:Form(
          key: _formKey,
          //设置这个 AutovalidateMode.onUserInteraction就会 对每个validator，在用户进行输入的时候自动进行校验。
          //如果不设置这个的话，就需要在点击“注册”的时候，通过_formKey.currentState as FormState).validate()来进行“手动”校验。
          // autovalidateMode: AutovalidateMode.onUserInteraction,
          child: Column(
            children: [
              Row(
                children: [
                  Container(
                    width: 75,
                    child:Text("手机号码：", style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.w600),) ,
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _phoneController,
                      decoration: InputDecoration(
                          hintText: "请输入手机号码（11位）",
                          border: InputBorder.none
                      ),
                      //validator用于校验，该方法返回的东西就是 校验失败后，提醒用户的提醒语。
                      //trim() 方法用于删除字符串的头尾空白符，空白符包括：空格、制表符 tab、换行符等其他空白符等。
                      validator: (value){
                        if(value!.trim().isEmpty){
                          return "手机号码不能为空";
                        }else if(value.trim().length!=11){
                          return "手机号码位数无效";
                        }
                        return null;
                      },
                    ),
                  )
                ],
              ),
              Row(
                children: [
                  Container(
                    width: 75,
                    child:Text("密码：", style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.w600),) ,
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _pwdController,
                      decoration: InputDecoration(
                          hintText: "请输入密码",
                          border: InputBorder.none
                      ),
                      obscureText: true,
                      validator: (value){
                        if(value!.isEmpty){
                          return "密码不能为空";
                        }
                        return null;
                      },
                    ),
                  )
                ],
              ),
              Row(
                children: [
                  Container(
                    width: 75,
                    child:Text("确认密码：", style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.w600),) ,
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _pwdConfirmController,
                      decoration: InputDecoration(
                          hintText: "请确认密码",
                          border: InputBorder.none
                      ),
                      obscureText: true,
                      validator: (value){
                        if(value!.isEmpty){
                          return "密码不能为空";
                        }else if(_pwdController.text != _pwdConfirmController.text){
                          return "两次密码不一致";
                        }
                        return null;
                      },
                    ),
                  )
                ],
              ),
              Row(
                children: [
                  Container(
                    width: 75,
                    child:Text("用户姓名：", style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.w600),) ,
                  ),
                  Expanded(
                    child: TextFormField(
                      controller: _unameController,
                      decoration: InputDecoration(
                          hintText: "请输入用户姓名",
                          border: InputBorder.none
                      ),
                      validator: (value){
                        if(value!.isEmpty){
                          return "用户姓名不能为空";
                        }
                        return null;
                      },
                    ),
                  )
                ],
              ),
              Row(
                children: [
                  Container(
                    width: 75,
                    child:Text("性别：", style: TextStyle(color: Colors.grey.shade700, fontWeight: FontWeight.w600),) ,
                  ),
                  Flexible(
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: Row(
                            children: [
                              Text("男"),
                              Radio(value: 1, groupValue: sex,
                                  onChanged: (value){setState(() {
                                sex = value!;//value系统判定是个 int?
                              });})
                            ],
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: Row(
                            children: [
                              Text("女"),
                              Radio(value: 0, groupValue: sex,
                                  onChanged: (value){setState(() {
                                sex = value!;//value系统判定是个 int?
                              });})
                            ],
                          ),
                        ),
                      ],
                    )
                  ),
                ],
              ),
              Padding(padding: EdgeInsets.only(bottom: 5)),
              Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                        style: ButtonStyle(
                          shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(5))),
                          backgroundColor: MaterialStateColor.resolveWith((states) {
                            //获取 焦点时/点击时 的颜色
                            if (states.contains(MaterialState.focused) || states.contains(MaterialState.pressed)) {
                              return Colors.green.shade500;
                            }
                            //默认状态使用灰色
                            return Colors.green.shade300;
                          }),
                        ),
                        onPressed: (){
                          register(_phoneController.text,_pwdController.text,_unameController.text,sex);
                        },
                        child: Text("注册",style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),)),
                  )
                ],
              ),
            ],
          ),
        )
      ),
    );
  }

  void register(id, pw, name, sex)async{
    if ((_formKey.currentState as FormState).validate()) {
      var res = await userApi.userRegister(id, pw, pw, sex);
      //这里务必 使用await 让对话框结束后，再进行页面跳转。如果不用await，那么就不会等待对话框，而是直接跳转
      await showConfirmDialog(context,"${res.code}:${res.message}");
      if(res.code==200){
        Navigator.pushNamed(context, "login");
      }
    }
  }
}



